<template>
  <page-view :title="false">
    <a-card :bordered="false">
      <a-row :gutter="8">
        <a-col :span="5">
          <a-input-search style="margin-bottom: 8px" placeholder="Search" @change="onChange" />
          <a-tree
            @expand="onExpand"
            :expandedKeys="expandedKeys"
            :autoExpandParent="autoExpandParent"
            :treeData="categoryTreeData"
            @select="onSelect"
          >
            <template slot="title" slot-scope="{title}">
              <span v-if="title.indexOf(searchValue) > -1">
                {{ title.substr(0, title.indexOf(searchValue)) }}
                <span
                  style="color: #f50"
                >{{ searchValue }}</span>
                {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
              </span>
              <span v-else>{{ title }}</span>
            </template>
          </a-tree>
        </a-col>
        <a-col :span="19">
          <div class="table-operator">
            <a-button type="primary" @click="handleCreate()">新增</a-button>
          </div>

          <a-table
            ref="table"
            :columns="columns"
            :rowKey="record => record.id"
            :dataSource="attributeList"
            :show-pagination="false"
          >
            <span slot="enable" slot-scope="text">{{ text | yesOrNotMapFilter }}</span>
            <span slot="sale" slot-scope="text">{{ text | yesOrNotMapFilter }}</span>

            <span slot="action" slot-scope="text, record">
              <a style="margin-right:10px;" href="javascript:;" @click="handleEdit(record)">编辑</a>
              <a href="javascript:;" @click="handleDel(record)">删除</a>
            </span>
          </a-table>
        </a-col>
      </a-row>
    </a-card>
    <attribute-modal ref="attributeModal" @ok="handleSaveOk" />
  </page-view>
</template>

<script>
import { PageView } from '@/layouts'
import AttributeModal from './AttributeModal'
import { categoryList, attributeList, attributeDelete } from '@/api/product'
export default {
  name: 'Attribute',
  components: {
    PageView,
    AttributeModal
  },
  data () {
    return {
      columns,
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      categoryTreeData: [],
      categorySearchData: [],
      selectCategory: {},
      attributeList: []
    }
  },
  methods: {
    onExpand (expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onChange (e) {
      const value = e.target.value
      const expandedKeys = this.categorySearchData
        .map(item => {
          if (item.title.indexOf(value) > -1) {
            return item.parentId
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true
      })
    },
    // handler
    handleSaveOk () {
      console.log('接受子組件的通知')
      this.loadAttributeList({
        categoryId: this.selectCategory.categoryId
      })
    },
    handleCreate () {
      if (this.selectCategory.isLeaf) {
        this.$refs.attributeModal.handleCreate(this.selectCategory)
      } else {
        this.$message.error('请选择叶子节点', 1)
      }
    },
    handleEdit (record) {
      this.$refs.attributeModal.handleEdit(this.selectCategory, record)
    },
    handleDel (record) {
      attributeDelete(record).then(res => {
        if (res.status === 0) {
          this.loadAttributeList({
            categoryId: this.selectCategory.categoryId
          })
          this.$message.success('成功')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    onSelect (selectedKeys, info) {
      console.log('onSelect', info)
      this.selectCategory = {
        categoryId: selectedKeys[0],
        isLeaf: info.node.isLeaf,
        label: info.node.label
      }
      if (this.selectCategory.isLeaf) {
        this.loadAttributeList({
          categoryId: this.selectCategory.categoryId
        })
      }
    },
    loadCategoryTreeData () {
      categoryList().then(res => {
        const treeData = []
        res.data.forEach(item => {
          const node = {
            title: item.name,
            label: item.name,
            key: item.id,
            id: item.id,
            parentId: item.parentId,
            isLeaf: item.leaf,
            scopedSlots: { title: 'title' }
          }
          if (item.parentId === 0) {
            treeData.push(node)
          }
          this.categorySearchData.push(node)
        })
        treeData.forEach(item => {
          setChildren(item, res.data)
        })
        this.categoryTreeData = treeData
        console.log(this.categoryTreeData)
      })
    },
    loadAttributeList (param) {
      attributeList(param).then(res => {
        this.attributeList = res.data
      })
    }
  },
  created () {
    this.loadCategoryTreeData()
  },
  filters: {
    yesOrNotMapFilter (value) {
      const yesOrNotMap = {
        true: '是',
        false: '否'
      }
      return yesOrNotMap[value]
    }
  }
}

function setChildren (pNode, list) {
  const children = getChildren(pNode, list)
  if (children.length !== 0) {
    pNode.children = children
    children.forEach(item => {
      setChildren(item, list)
    })
  }
}

function getChildren (pNode, list) {
  const children = []
  list.forEach(item => {
    if (pNode.id === item.parentId) {
      const cNode = {
        title: item.name,
        label: item.name,
        key: item.id,
        id: item.id,
        parentId: item.parentId,
        isLeaf: item.leaf,
        scopedSlots: { title: 'title' }
      }
      children.push(cNode)
    }
  })
  return children
}

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    key: 'id',
    width: '12%'
  },
  {
    title: '属性名',
    dataIndex: 'name',
    key: 'name',
    width: '12%'
  },
  {
    title: '销售属性',
    dataIndex: 'sale',
    key: 'sale',
    scopedSlots: { customRender: 'sale' }
  },

  {
    title: '开启',
    dataIndex: 'enable',
    key: 'enable',
    scopedSlots: { customRender: 'enable' }
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' },
    width: '20%'
  }
]
</script>
